﻿using System;
using System.Collections.Generic;

namespace K9Nano.Share.Extensions
{
    public static class CommonExtensions
    {
        public static bool IsValueNull(this object obj)
        {
            if (obj == null) return true;
            var type = obj.GetType();
            if (type.IsValueType)
            {
                switch (obj)
                {
                    case int i:
                        return i == 0;
                    case long l:
                        return l == 0L;
                    case short s:
                        return s == 0;
                    case float f:
                        return f.AlmostEquals(0F);
                    case double d:
                        return d.AlmostEquals(0D);
                    case DateTime dt:
                        return dt == default;
                    default:
                        // enum \ struct ?
                        return false;
                }
            }

            if (type == typeof(DateTime?))
            {
                var dt2 = (DateTime?) obj;
                return dt2.Value == default;
            }


            if (obj is string str)
            {
                return string.IsNullOrWhiteSpace(str);
            }

            return false;
        }

        public static bool AlmostEquals(this double double1, double double2, double precision = 0.0000001)
        {
            return Math.Abs(double1 - double2) <= precision;
        }

        public static bool AlmostEquals(this float float1, float float2, float precision = 0.0000001F)
        {
            return Math.Abs(float1 - float2) <= precision;
        }

        public static void Extends<TKey, TValue>(this Dictionary<TKey, TValue> a, Dictionary<TKey, TValue> b)
        {
            foreach (var key in a.Keys)
            {
                if (b.ContainsKey(key))
                {
                    var value = b[key];
                    if (!value.IsValueNull())
                    {
                        a[key] = b[key];
                    }
                }
            }
        }

        public static DateTime ToDayStart(this DateTime time)
        {
            return new DateTime(time.Year, time.Month, time.Day);
        }
    }
}